<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="./css/main.css" />
  </head>
  <body>
    <div class="dialog" id="dialog">
      <div class="content">
        <button class="icon-close" data-action="close">x</button>

        <form name="form">
          <p>
            <label>姓名</label>
            <input type="text" name="uname" />
          </p>

          <p>
            <label>性别</label>
            <input type="radio" checked name="gender" value="1" /> 男
            <input type="radio" name="gender" value="2" /> 女
          </p>
          <p>
            <label>邮箱</label>
            <input type="text" name="email" />
          </p>
          <p>
            <label>密码</label>
            <input type="password" name="password" />
          </p>
          <p>
            <label>爱好</label>
            <input type="checkbox" name="hobbys" value="css" /> CSS
            <input type="checkbox" name="hobbys" value="html" /> HTML
            <input type="checkbox" name="hobbys" value="js" /> JS
          </p>
          <p>
            <label>城市</label>
            <select name="city">
              <option value="">请选择</option>
              <option value="nj">南京</option>
              <option value="bj">北京</option>
              <option value="sh">上海</option>
              <option value="sz">苏州</option>
            </select>
          </p>
          <p>
            <button data-action="save" type="button">保存</button>
          </p>
        </form>
      </div>
    </div>

    <h1>hello APP</h1>

    <button data-action="open">open</button>

    <script>
      const dialog = document.getElementById("dialog");
      //收集表单值
      let formData = {};
      // input事件，实时获取表单值
      document.form.oninput = function () {
        const fd = new FormData(document.form);
        formData = Object.fromEntries(fd.entries());
        // getAll 可以对多选值获取，返回数组
        formData.hobbys = fd.getAll("hobbys");
      };

      const actions = {
        save() {
          console.log(formData);
        },
        close() {
          dialog.style.display = "none";
        },
        open() {
          dialog.style.display = "flex";
        },
      };
      document.body.onclick = function (e) {
        // 获取事件行为标识
        const action = e.target.dataset.action;
        // 过滤条件，不符合条件代码就不执行
        if (action === undefined || actions[action] === undefined) return;
        // 修改方法中this
        actions[action].call(e.target);
        // actions[action]();
      };
    </script>
  </body>
</html>
